7. Strings

  1. Single quoted strings and double quoted strings.
    • Let's try the next example.
      verse0 = "What a wonderful world!"
      print(verse0)
      verse1 = 'What a beautiful world!'
      print(verse1)
      
    • How are they different? A single quote symbol can be included in double quoted strings. In the reverse way, a double quote symbol can be included in single quoted strings.
      Let's try the next example.
      verse0 = "What's your name?"
      print(verse0)
      verse1 = 'The color of rose: "Red"'
      print(verse1)
      
    • How to include a single quote symbol in single quoted strings? How to include a double quote symbol in double quoted strings?
    • Escape sequences come for the above questions.
      • \' - single quote character
      • \" - double quote character
      • \n - new line character
      • \t - tab character
      • \\ - back slash, '\', character
      • Let's try the next example.
        verse0 = "What's your name?"
        print(verse0)
        verse1 = 'What\'s your name?'
        print(verse1)
        print('\n\n')
        verse2 = 'The color of rose: "Red"'
        print(verse2)
        verse3 = "The color of rose: \"Red\""
        print(verse3)
        verse4 = "What a beautiful world!\nWhat a beautiful world!"
        print(verse4)
        
  2. String over multiple lines
    • How to define a string over multiple lines? Let's try the next example. How are the two examples different?
      verse0 = "What a beautiful world!\
      What a wonderful world!"
      print(verse0)
      verse1 = "What a beautiful world!\n\
      What a wonderful world!"
      print(verse1)
      
    • How to define a string over multiple lines? Let's try another example of three single quotes.
      verse0 = '''What a beautiful world!
      
      What a beautiful world!'''
      print(verse0)
      
    • \n\ at the end of line can be ommitteed when we use three single quoted strings.
  3. Comments over multiple lines
    • We have used single line comments using #.
      print("What a beautiful world!\nWhat a wonderful world!")  # What will be printed?
      
    • How to use multiple lines for a comment? Let's try the next example.
      """
      printBoard(board)
        board: n x n game board
        return: 
      """
      def printBoard(board):
          for r in range(len(board)):
              for c in range(len(board)):
                  print(board[r][c], end='')  # end='' gives no new line
                  if c == 0 or c == 1:
                      print('|', end='')
              print()  # new line
              if r != 2:
                print('-+-+-')
      
      '''
      An example board, and
      print the board
      '''
      board = [[' ', 'O', ' '], ['X', ' ', 'X'], [' ', ' ', ' ']]  # a tic-tac-toe board
      printBoard(board)
      
    • Multiple line comments - anything in between """ and """, or anything in between ''' and '''
  4. Strings as sequence data type like lists and tuples
    • How to access each character in a string - indexing
      verse = "What a wonderful world!"
      print(verse[2])
      
    • How to slice a substring from a string - slicing
      verse = "What a wonderful world!"
      print(verse[7:16])  # 9 (= 16 - 7) characters from verse[7]
      print(verse[:7])  # 7 (= 7 - 0) characters from verse[0]
      print(verse[7:])  # all the characters from verse[7]
      
    • How to get the length of a string - len()
      verse = "What a wonderful world!"
      print(len(verse))  # ???
      
    • in and not in operations with strings
      verse = "What a wonderful world!"
      if 'winderful' in verse:
          print('Wonderful verse it is!')
      elif 'winderful' not in verse:
          print('Poor verse it is!')
      
  5. How to insert a string in a string
    • A case - We have a base sentence that includes name and age. Can we use the base sentence for different people?
    • Let's try the next example for the above case.
      name = 'Dave'
      feeling = 'Good'
      sentence1 = "Hello " + name + "!" + " Are you feeling " + feeling + ' today?'
      print(sentence1)
      name = 'Tom'
      feeling = 'Excellent'
      sentence2 = "Hello " + name + "!" + " Are you feeling " + feeling + ' today?'
      print(sentence2)
      
    • In the above example, sentences have to be constructed separately.
    • Is there any way to use a base sentence and replance name and feeling? Let's try the next example.
      base = "Hello %s! Are you feeling %s today?"
      print(base)
      name = 'Dave'
      feeling = 'Good'
      sentence1 = base%(name, feeling)
      print(sentence1)
      sentence2 = base%('Tom', 'Excellent')
      print(sentence2)
      
  6. String methods
    • .upper() - Convert all the characters to uppercase characters
      .lower() - Convert all the characters to lowercase characters
      halsays = 'Good morning, Dave!'
      print(halsays)
      halsays.upper()
      print(halsays)  # ???
      halsays = halsays.upper()
      print(halsays)
      halsays = halsays.lower()
      print(halsays)
      
    • An example how to use .upper() or .lower()
      sum = 0
      count = 0
      while True:
          sum = sum + float(input("GPA: "))
          count += 1
          answer = input("Would you like to keep entering more GPAs? Say Yes or yes! ")
          answer = answer.lower()
          if (answer != 'yes'):  # We don't have to check 'Yes' and 'YES'
              break  # break out of the loop
      
      average = sum / count
      print("Average = " + str(average))
      
    • .isupper() - is if uppercase characters
    • .islower() - is if lowercase characters
    • .isalpha() - is if alphabets
    • .isalnum() - is if alphabets and numbers
    • .isdecimal() - is if numbers
    • .isspace() - is if spaces
    • .istitle() - is if words that begin with an uppercase letter followed by only lowercase letters
    • An example how to use .startswith() or .endswith()
      title = "MATH 1390 Discrete Structures 2"
      if (title.startswith('COMP') or title.startswith('comp')):
          print("Comp course")
      elif (title.startswith('MATH') or title.startswith('math')):
          print("Math course")
      else:
          print("Not Comp nor Math")
          
      if (title.endswith('1')):
          print("First course")
      elif (title.endswith('2')):
          print("Second course")
      else:
          print("Third or above")
      
    • .rjust(), .ljust(), .center - text justification in strings
      verse = "What a wonderful day!"  # 21 characters
      print('--' + verse.rjust(40) + '--')
      print('--' + verse.ljust(40) + '--')
      print('--' + verse.center(40) + '--')
      print(verse.rjust(40, '-'))
      print(verse.ljust(40, '-'))
      print(verse.center(40, '-'))
      
    • .rstrip(), .lstrip(), .strip - How to remove white spaces in strings
      verse = "  What a wonderful day!  "
      print('--' + verse.rstrip() + '--')
      print('--' + verse.lstrip() + '--')
      print('--' + verse.strip() + '--')
      
  7. Covert a string to a list, and convert a list/tuple to a string
    • .join() - Converts a list or tuple of string values to a string
      student = ['John', '20', 'COMP']
      strstudent = ','.join(student)  # comma separated data
      print(strstudent)
      student = ('John', '20', 'COMP')  # a tuple
      strstudent = ' '.join(student)  # space separated data
      print(strstudent)
      student = ['John', 20, 'COMP']  # ???
      strstudent = ','.join(student)
      print(strstudent)
      
    • How to convert a list of any values to a string?
      student = ['John', 20, 'COMP']  # ???
      studentstr = []
      for item in student:
          studentstr.append(str(item))
      strstudent = ','.join(studentstr)
      print(strstudent)
      # or
      studentstr = [str(item) for item in student]  # it is interesting.
      strstudent = ','.join(studentstr)
      print(strstudent)
      
    • Note that any string can be a separator, and only a list or tuple of all string values is converted to a string with .join().
    • .split() - Converts a string to a list of string values
      strstudent = 'John,20,COMP'  # comma separated data
      student = strstudent.split(',')
      print(student)
      strstudent = 'John 20 COMP'  # space separated data
      student = tuple(strstudent.split(' '))  # how to convert a string to a tuple
      print(student)
      
    • Note that any string can be used as a separator with .split().
    • .partition() - Divides a string to a tuple of two parts with a separator
      strstudent = 'John,20,COMP'  # comma separated data
      student = strstudent.partition(',')
      print(student)
      strstudent = 'John 20 COMP'  # space separated data
      student = strstudent.partition(' ')
      print(student)
      
    • Note that any string can be used as a separator with .partition().
  8. Characters as numbers
    • When a character is stored in computer memories, the corresponding number, that is called as Unicode code point, of the character is stored. Note that computer memories are arrays of bytes.
    • How to see the unicode code point of a character - ord(), chr()
      print(ord('A'))
      print(ord('ㄷ'))  # 'ㄷ' ???
      print(chr(65))
      
    • Comparison of strings - With the unicode code points, we can say which one of two strings is smaller.
      name0 = 'Tom'
      name1 = 'Hanna'
      if (name0 < name1):
          print(name0 + ' is smaller than ' + name1)
      else:
          print(name0 + ' is not smaller than ' + name1)
      
  9. Programming exercises
    • Write a program that prints the next triangle using text justification.
          *
         ***
        *****
       *******
      *********
      
    • Write a program that prints the next triangle using text justification.
      *****
       ****
        ***
         **
          *
      
    • Write a program that reads a string and converts it to a tuple. E.g., '(10,M)' should be convergted to a tuple ('10','M').
  10. References